package com.aiti.ai.tool;

import com.aiti.ai.dto.ai.BoChaWebSearchQueryParamDto;
import com.aiti.ai.dto.ai.BoChaWebSearchResponse;
import com.aiti.ai.utils.WebSearchUtils;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @description: BochaAPITool
 * @auth Administrator
 * @date 2025-03-03 17:22
 **/
@Component
@Slf4j
public class BochaAPITool {

    @Resource
    private WebSearchUtils webSearchUtils;

    /**
     * 使用Bocha Web Search API 进行搜索互联网网页
     * 需要配置环境变量 Bocha_api_key
     * @param enterpriseName
     * @return
     */
    @Tool("使用Bocha Web Search API 进行搜索互联网网页，输入应为企业名称，输出将返回搜索结果的详细信息，包括网页标题、网页URL、网页摘要、网站名称")
    public String bocha_websearch_tool(@P("企业名称")String enterpriseName) {
        log.info("回调博查tool，参数：{}", enterpriseName);

        BoChaWebSearchQueryParamDto paramDto = new BoChaWebSearchQueryParamDto();
        paramDto.setCount(5);
        paramDto.setQuery(enterpriseName);
        paramDto.setSummary(true);

        BoChaWebSearchResponse response = webSearchUtils.boChaWebSearch(paramDto, System.getenv("Bocha_api_key"));
        if(response == null) {
            return "网页搜索失败";
        }

        List<BoChaWebSearchResponse.WebPageValue> value = response.getData().getWebPages().getValue();
        StringBuilder sb = new StringBuilder();
        for(BoChaWebSearchResponse.WebPageValue v: value) {
            sb.append("网页标题：").append(v.getName()).append("\n");
            sb.append("网页URL：").append(v.getUrl()).append("\n");
            sb.append("网页摘要：").append(v.getSummary()).append("\n");
            sb.append("网站名称：").append(v.getSiteName()).append("\n\n");
        }

        return sb.toString();
    }


}
